﻿using AduSkin.Controls.Metro;
using HsServerHa.Entity.Models;
using HsServerHa.UserControls.Dialog;
using HsServerHa.Utility.DataHelper;
using HsServerHa.Utility.SQLite;
using HsServerHa.WinPage;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;

namespace HsServerHa.UserControls
{
    /// <summary>
    /// SetMasterSlave.xaml 的交互逻辑
    /// </summary>
    public partial class SetMasterSlave : MetroWindow
    {
        public static string MasterSlaveName { get; set; }
        public SetMasterSlave()
        {
            InitializeComponent();
        }

        public void SetMasterSalve()
        {
            this.Dispatcher.Invoke(new Action(() => {
                if (string.IsNullOrEmpty(MasterSlaveName))
                {
                    AduMessageBoxs.Show("请选择！");
                    return;
                }

                MessageBoxResult dr = AduMessageBox.ShowOKCancel($"你确定选择{MasterSlaveName}吗？", "系统提示!", "确定", "取消");

                if (dr == MessageBoxResult.OK)
                {
                    if (MasterSlaveName == "从机")
                        App.isMaster = false;
                    else
                        App.isMaster = true;

                    this.loading.Visibility = Visibility.Visible;
                    this.Setting.IsEnabled = false;

                SetMasterSalveData:
                    //查询一下配置网卡了没
                    //var sqlVM = "select * from VirtuallyManage";
                    //var dt = DbHelperSQLite.Query(sqlVM)?.Tables?[0];

                    List<VirtuallyManageEntity> list = SQLiteHelper.Table<VirtuallyManageEntity>().ToList();

                    if (list.Count > 0)
                    {
                        //List<VirtuallyManageEntity> list = DataHelpers.ConvertToModel<VirtuallyManageEntity>(dt);
                        if (MasterSlaveName == "主机")
                        {
                            //记录绑定数据，目前还没绑定就临时把主要数据加上去
                            SQLiteHelper.ExecuteSql($"insert into  MasterSlaveBind (MasterIP,SlaveIP,IsMaster,VirtuallyIP,CreateTime)  values('{list[0].CurrIP}','','true','{list[0].VirtuallyIP}','{DateTime.Now.ToString()}') ");
                        addXt:
                            AlertTemp alertTempXt = new AlertTemp(new AddHeart(), "添加心跳", "500", "500");
                            alertTempXt.ShowDialog();

                            //var dtXt = DbHelperSQLite.Query("select * from  HeartManage where IsLocal='true'")?.Tables?[0];
                            List<HeartEntity> heartList = SQLiteHelper.Table<HeartEntity>().Where(x => x.IsLocal == "true").ToList();
                            //查询心跳
                            if (heartList.Count == 0)
                            {
                                AduMessageBoxs.Show("请添加心跳");
                                goto addXt;
                            }
                            //List<HeartEntity> heartList = DataHelpers.ConvertToModel<HeartEntity>(dtXt);
                            IniFileConfig.Current.SetStringValue("UserConfig", "IsMainPC", "true");
                            App.MasterIP = list[0].CurrIP;
                            App.XtIP = heartList[0].HeartIP;
                            LoggerHelper.SetInfo("设置主机成功", "主从选择");
                            LoggerHelper.SetInfo("设置心跳成功", "主从选择");
                        }
                        else
                        {
                            App.MasterIP = "";
                            //跳出加入主机的页面
                            AlertTemp alertTempJoinMaster = new AlertTemp(new JoinMaster(), "加入主机集群", "500", "500");
                            alertTempJoinMaster.ShowDialog();

                            //查询绑定过主机信息没
                            //var bindDt = DbHelperSQLite.Query("select  * from MasterSlaveBind")?.Tables?[0];
                            //var bidList = DataHelpers.ConvertToModel<MasterSlaveBindEntity>(bindDt);
                            var bidList = SQLiteHelper.Table<MasterSlaveBindEntity>().ToList();


                            if (bidList.Count > 0)
                            {
                            addXt:
                                AlertTemp alertTempXt = new AlertTemp(new AddHeart(), "添加心跳", "500", "500");
                                alertTempXt.ShowDialog();
                                //var dtXt = DbHelperSQLite.Query("select * from  HeartManage where IsLocal='true'")?.Tables?[0];
                                var listXt = SQLiteHelper.Table<HeartEntity>().Where(x => x.IsLocal == "true").ToList();

                                //查询心跳
                                if (listXt.Count == 0)
                                {
                                    AduMessageBoxs.Show("请添加心跳");
                                    goto addXt;
                                }
                                //var listXt = DataHelpers.ConvertToModel<HeartEntity>(dtXt);
                                IniFileConfig.Current.SetStringValue("UserConfig", "IsMainPC", "false");
                                App.XtIP = listXt[0].MasterHeartIPBind;
                                LoggerHelper.SetInfo("设置从机成功", "主从选择");
                                LoggerHelper.SetInfo("设置心跳成功", "主从选择");
                            }
                            else
                            {
                                goto peizJoin;
                            }
                        }
                    }
                    else
                    {
                        AlertTemp alertTemp = new AlertTemp(new VirtuallyIPSetting(), "设置网卡", "500", "500");
                        alertTemp.ShowDialog();
                        //var dt1 = DbHelperSQLite.Query(sqlVM)?.Tables?[0];
                        list = SQLiteHelper.Table<VirtuallyManageEntity>().ToList();
                        if (list.Count > 0)
                        {
                            LoggerHelper.SetInfo("网卡设置成功", "主从选择");
                            goto SetMasterSalveData;

                        }
                        else
                        {
                            goto End;  
                        }
                    }


                    MainWindow mainWindow = new MainWindow();
                    mainWindow.Show();
                    mainWindow.Activate();
                    this.IsEnabled = true;
                    this.Hide();
                    return;
                peiz:
                    AduMessageBoxs.Show("请配置虚拟网卡！");
                peizJoin:
                    AduMessageBoxs.Show("请加入主机集群");
 
                End://暂时去掉上面的弹框，同时取消延时，因为没有延时效果
                    //Task.Delay(2000);
                    this.loading.Visibility = Visibility.Hidden;
                    this.Setting.IsEnabled = true;
                }

            }));



        }

        private async void AduFlatButton_Click(object sender, RoutedEventArgs e)
        {

            SetMasterSalve();
        }


        private async void login_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                SetMasterSalve();
            }
        }

        private void Save_b_MouseDown(object sender, MouseButtonEventArgs e)
        {
            this.Save_b.Background = new SolidColorBrush(Colors.Thistle);
            this.Master_b.Background = new SolidColorBrush(Colors.White);
            MasterSlaveName = "从机";
            //App.isMaster = false;
        }

        private void Master_b_MouseDown(object sender, MouseButtonEventArgs e)
        {
            this.Master_b.Background = new SolidColorBrush(Colors.Thistle);
            this.Save_b.Background = new SolidColorBrush(Colors.White);
            MasterSlaveName = "主机";
            //App.isMaster = true;
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            Application.Current.Shutdown();
        }
    }
}